<template>
    <div>
        <el-upload
            v-model="url"
            :action="uploadUrl"
            :data="uploadData"
            :headers="headerData"
            :multiple="false"
            :show-file-list="false"
            :limit="1"
            list-type="picture-card"
            :on-success="handleSuccess"
            class="relative overflow-hidden rounded lv-upload-box"
            @mouseenter="hoverShow = true"
            @mouseleave="hoverShow = false"
            ref="uploadRef"
        >
            <template #default>
                <div v-if="url">
                    <div
                        class="absolute top-0 flex items-center justify-around w-full h-full bg-black bg-opacity-20"
                        v-if="hoverShow"
                    >
                        <el-icon size="26px" color="#fff" @click.stop="handlePictureCardPreview">
                            <ZoomIn />
                        </el-icon>
                        <el-icon size="26px" color="#fff" @click.stop="handleRemove">
                            <Delete />
                        </el-icon>
                    </div>
                    <img :src="url" fit="contain" />
                </div>

                <el-icon v-else><Plus /></el-icon>
            </template>
        </el-upload>
        <div class="text-xs mt-1 text-[#595959]">
            <span class="text-[#F53F3F] text-sm" v-if="required">*</span>{{ info }}
        </div>
        <el-image-viewer v-if="showPreview" :url-list="[url]" @close="showPreview = false" />
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { Delete, Plus, ZoomIn } from '@element-plus/icons-vue'
import { getToken } from '@/utils/store';
const url = defineModel<string>()
const props = defineProps<{ info?: string; required?: boolean }>()
const uploadUrl = import.meta.env.SYSTEM_BASE_API + '/file/img' // 图片上传地址
const uploadData = {
    // 上传图片携带参数 地址 + 后端对应的服务名
    isCompress: 1,
    path: 'goods'
}
const headerData = {
  satoken: getToken()
}
const uploadRef = ref()
const showPreview = ref(false)
const hoverShow = ref(false)
const handlePictureCardPreview = () => {
    showPreview.value = true
}
const handleRemove = () => {
    url.value = ''
    uploadRef.value?.clearFiles()
}
const handleSuccess = (response: any) => {
    console.log(response);
    
    if (response.code === 0) {
        url.value = response.data
    }
}
</script>

<style lang="scss">
.lv-upload-box {
    .el-upload-list--picture-card {
        --el-upload-list-picture-card-size: 106px !important;
        --el-upload-picture-card-size: 106px !important;
    }
    .el-upload--picture-card {
        --el-upload-list-picture-card-size: 106px !important;
        --el-upload-picture-card-size: 106px !important;
    }
}
</style>
